﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;

namespace NotWindowsStoreMetro
{
    public class AppInstallerService
    {
        public static async Task WriteFile(string fileName, byte[] data)
        {
            var folder = KnownFolders.DocumentsLibrary;
            StorageFile file = await folder.CreateFileAsync(fileName + ".nwsapp", CreationCollisionOption.ReplaceExisting);
            var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);
            var fileOutputStream = fileStream.GetOutputStreamAt(0);
            var writer = new DataWriter(fileOutputStream);
            var dataStream = new MemoryStream(data);
            int read;
            byte[] dataBuffer = new byte[1024];
            while ((read = dataStream.Read(dataBuffer, 0, dataBuffer.Length)) > 0)
            {
                byte[] temp = new byte[read];
                Array.Copy(dataBuffer, 0, temp, 0, read);
                writer.WriteBytes(temp);
            }
            await writer.StoreAsync();
            await fileOutputStream.FlushAsync();
        }
    }
}
